import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_study/api/api_service.dart';
import 'package:flutter_study/config/ConstString.dart';
import 'package:flutter_study/model/base_change_notifier_model.dart';
import 'package:flutter_study/model/issue_model.dart';
import 'package:flutter_study/page/video_detail_page.dart';
import 'package:flutter_study/util/date_util.dart';
import 'package:flutter_study/util/navigator_manager.dart';
import 'package:flutter_study/util/toast_util.dart';
import 'package:flutter_study/widget/loading_container.dart';
import 'package:flutter_study/widget/provider_widget.dart';
import 'package:flutter_study/widget/search_video_widget_item.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class VideoSearchPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      decoration: BoxDecoration(color: Colors.white),
      child: SafeArea(
        child: ProviderWidget<VideoSearchModel>(
          model: VideoSearchModel(),
          onModelInit: (model) {
            model.getKeyWords();
          },
          builder: (context, value, child) {
            return Column(
              children: [
                _searchBar(value, context),
                _searchContent(value),
              ],
            );
          },
        ),
      ),
    ));
  }

  _searchBar(VideoSearchModel model, BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(top: 10, right: 16),
      child: Row(
        children: [
          IconButton(
              icon: Icon(
                Icons.arrow_back,
                size: 20,
                color: Colors.black26,
              ),
              onPressed: () {
                NavigatorManager.back();
              }),
          Expanded(
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 30),
              child: TextField(
                autofocus: false,
                onSubmitted: (value) {
                  model.query = value;
                  model.loadMore(loadMore: false);
                },
                textInputAction: TextInputAction.search,
                decoration: InputDecoration(
                    contentPadding: EdgeInsets.only(bottom: 15),
                    fillColor: Color(0x0D000000),
                    filled: true,
                    border: OutlineInputBorder(
                        borderSide: BorderSide.none,
                        borderRadius: BorderRadius.circular(20)),
                    hintText: ConstString.interest_video,
                    hintStyle: TextStyle(fontSize: 13),
                    prefixIcon: Icon(
                      Icons.search,
                      size: 20,
                      color: Colors.black26,
                    )),
              ),
            ),
          ),
          Offstage(
            offstage: !Platform.isAndroid,
            child: IconButton(
              icon: Icon(
                Icons.keyboard_voice,
                color: Colors.black26,
              ),
              onPressed: () {
                _showSpeechDialog(model);
              },
            ),
          )
        ],
      ),
    );
  }

  _showSpeechDialog(VideoSearchModel model) {}

  _searchContent(VideoSearchModel model) {
    return Expanded(
      flex: 1,
      child: Stack(
        children: [
          _keyWordWidget(model),
          _searchVideoWidget(model),
          _emptyWidget(model),
        ],
      ),
    );
  }

  _keyWordWidget(VideoSearchModel model) {
    return Offstage(
      offstage: model.hideKeyWord,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.only(top: 25),
            child: Center(
              child: Text(
                ConstString.hot_key_word,
                style: TextStyle(fontSize: 16, color: Colors.black),
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(10, 20, 10, 0),
            child: Wrap(
              alignment: WrapAlignment.center,
              spacing: 6,
              runSpacing: 10,
              children: _keyWordWidgets(model),
            ),
          )
        ],
      ),
    );
  }

  _keyWordWidgets(VideoSearchModel model) {
    return model.keyWords.map((e) {
      return GestureDetector(
        onTap: () {
          _hideTextInput();
          model.query = e;
          model.loadMore(loadMore: false);
        },
        child: Container(
          padding: const EdgeInsets.fromLTRB(14, 8, 14, 8),
          decoration: BoxDecoration(
            color: Color(0x1A000000),
            borderRadius: BorderRadius.circular(20),
          ),
          child: Text(
            e,
            style: TextStyle(fontSize: 12, color: Colors.black45),
          ),
        ),
      );
    }).toList();
  }

  _hideTextInput() {
    SystemChannels.textInput.invokeMethod("TextInput.hide");
  }

  _searchVideoWidget(VideoSearchModel model) {
    return Offstage(
      offstage: model.dataList == null || model.dataList.length == 0,
      child: LoadingContainer(
        loading: model.loading,
        error: model.error,
        retry: model.retry,
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.only(top: 20, bottom: 20),
              child: Text(
                "— 「${model.query}」搜索结果共${model.total}个 —",
                style: TextStyle(
                    color: Colors.black54,
                    fontWeight: FontWeight.bold,
                    fontSize: 14),
              ),
            ),
            Expanded(
              flex: 1,
              child: SmartRefresher(
                enablePullDown: false,
                enablePullUp: true,
                onLoading: model.loadMore(),
                controller: model.refreshController,
                child: ListView.builder(
                  itemCount: model.dataList.length,
                  itemBuilder: (context, index) {
                    return SearchVideoWidgetItem(item: model.dataList[index]);
                  },
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  _emptyWidget(VideoSearchModel model) {
    return Offstage(
      offstage: model.hideEmpty,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.sentiment_dissatisfied,
              size: 60,
              color: Colors.black54,
            ),
            Padding(
              padding: EdgeInsets.only(top: 5),
              child: Text(
                ConstString.no_data,
                style: TextStyle(fontSize: 15, color: Colors.black54),
              ),
            )
          ],
        ),
      ),
    );
  }
}

class VideoSearchModel extends BaseChangeNotifierModel {
  String query = "";
  String _nextPageUrl;
  bool loading = true;
  bool error = false;
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  bool hideKeyWord = false;
  int total = 0;
  List<String> keyWords = [];
  List<Item> dataList = [];

  bool hideEmpty = true;

  getData(bool loadMore, String url) {
    ApiService.getData(url, success: (result) {
      Issue issue = Issue.fromJson(result);
      loading = false;
      error = false;
      total = issue.total;
      if (!loadMore) {
        dataList.clear();
        dataList.addAll(issue.itemList);
        hideEmpty = dataList.length > 0;
      } else {
        dataList.addAll(issue.itemList);
        hideEmpty = true;
      }
      dataList.removeWhere((element) => element.data.cover == null);
      _nextPageUrl = issue.nextPageUrl;
      hideKeyWord = true;
      refreshController.loadComplete();
    }, fail: (e) {
      ToastUtil.showError(e.toString());
      loading = false;
      if (!loadMore) error = true;
      refreshController.loadFailed();
    }, complete: () {
      notifyListeners();
    });
  }

  loadMore({bool loadMore = true}) {
    String url;
    if (loadMore) {
      if (_nextPageUrl == null) {
        refreshController.loadNoData();
        return;
      } else {
        url = _nextPageUrl;
        getData(loadMore, url);
      }
    } else {
      _reset();
      url = ApiService.search_url + query;
      getData(loadMore, url);
    }
  }

  _reset() {
    loading = true;
    notifyListeners();
  }

  retry() {
    loadMore(loadMore: false);
  }

  void getKeyWords() {
    ApiService.getData(ApiService.keyword_url, success: (result) {
      List data = result as List;
      keyWords = data.map((e) => e.toString()).toList();
    }, fail: (e) {
      ToastUtil.showError(e.toString());
    }, complete: () {
      notifyListeners();
    });
  }
}
